import {
    GuidedDraggingTool
} from "../EnlargeFile/GuidedDraggingTool"; //引入基准线功能
import ironShoesImg from '@/assets/ironShoes.png'
import carHeadImg from '@/assets/car.png'

export default {
    data() {
        return {}
    },
    methods: {
        // 初始化
        init() {
            let _this = this;
            if (window.goSamples) goSamples(); // 初始化这些示例——不需要调用
            let $ = go.GraphObject.make; // 为了定义模板的简洁性
            this.myDiagram = $(
                go.Diagram,
                "myDiagramDiv", // 必须命名或引用DIV HTML元素
                {
                    // isReadOnly: true, //只读
                    hoverDelay: 40, // 控制在显示装饰之前静止等待的时间（毫秒）
                    scale: 1.0, //初始视图大小比例
                    minScale: 0.01, //最小视图的缩小比例
                    maxScale: 52.05, //最大视图的放大比例
                    draggingTool: new GuidedDraggingTool(), // defined in GuidedDraggingTool.js
                    "draggingTool.horizontalGuidelineColor": "red", //水平基准线颜色
                    "draggingTool.verticalGuidelineColor": "blue", //竖直基准线颜色
                    "draggingTool.centerGuidelineColor": "#00FF55", //中心基准线颜色
                    "draggingTool.guidelineWidth": 1, //基准线宽度
                    "undoManager.isEnabled": true, // 启用撤消ctrl+z和重做ctrl+y
                    padding: new go.Margin(10, 5, 10, 5), // 整个图的内边距
                }
            );
            //生成右键菜单按钮
            function makeButton(text, action, visiblePredicate) {
                let GO = go.GraphObject.make;
                return GO(
                    "ContextMenuButton",
                    GO(go.TextBlock, text), {
                        click: action,
                        padding: 2,
                        background: "#F5F5F5",
                    },
                    // don't bother with binding GraphObject.visible if there's no predicate
                    visiblePredicate ?
                    new go.Binding("visible", "", function (o, e) {
                        return o.diagram ? visiblePredicate(o, e) : false;
                    }).ofObject() : {}
                );
            }
            // 右键菜单
            let partContextMenu = $(
                "ContextMenu",
                makeButton(
                    "剪切",
                    function (e, obj) {
                        e.diagram.commandHandler.cutSelection();
                    },
                    function (o) {
                        return o.diagram.commandHandler.canCutSelection();
                    }
                ),
                makeButton(
                    "复制",
                    function (e, obj) {
                        e.diagram.commandHandler.copySelection();
                    },
                    function (o) {
                        return o.diagram.commandHandler.canCopySelection();
                    }
                ),
                makeButton(
                    "粘贴",
                    function (e, obj) {
                        e.diagram.commandHandler.pasteSelection(
                            e.diagram.toolManager.contextMenuTool.mouseDownPoint
                        );
                    },
                    function (o) {
                        return o.diagram.commandHandler.canPasteSelection(
                            o.diagram.toolManager.contextMenuTool.mouseDownPoint
                        );
                    }
                ),
                makeButton(
                    "删除",
                    function (e, obj) {
                        e.diagram.commandHandler.deleteSelection();
                    },
                    function (o) {
                        return o.diagram.commandHandler.canDeleteSelection();
                    }
                )
            );
            /**
             * @description 线的缩放点样式
             * @param {String Arrary} pointNum 全部显示就传all,显示指定位置传['Top','Left']
             */
            function zoomPointStyle(pointNum) {
                let dirList = ['TopLeft', 'Top', 'TopRight', 'Left', 'Right', 'BottomLeft', 'Bottom', 'BottomRight'];
                let arr = []
                dirList.forEach(item => {
                    let obj = $(go.Shape, {
                        alignment: go.Spot[item],
                        cursor: "nw-resize",
                        desiredSize: new go.Size(6, 6),
                        fill: "transparent",
                        stroke: "rgba(0,191,255,0.5)",
                        desiredSize: new go.Size(8, 8),
                        strokeWidth: 2,
                    })
                    if (pointNum === 'all') {
                        arr.push(obj)
                    } else {
                        pointNum.forEach(a => {
                            if (a === item) {
                                arr.push(obj)
                            }
                        })
                    }
                })
                // let pointList = [{
                //         loc: 'topLeft',
                //         data: $(go.Shape, { //左上
                //             alignment: go.Spot.TopLeft,
                //             cursor: "nw-resize",
                //             desiredSize: new go.Size(6, 6),
                //             fill: "lightblue",
                //             stroke: "deepskyblue"
                //         }),
                //     },
                //     {
                //         loc: 'top',
                //         data: $(go.Shape, { //上
                //             alignment: go.Spot.Top,
                //             cursor: "n-resize",
                //             desiredSize: new go.Size(6, 6),
                //             fill: "lightblue",
                //             stroke: "deepskyblue"
                //         }),
                //     },
                //     {
                //         loc: 'topRight',
                //         data: $(go.Shape, { //上右
                //             alignment: go.Spot.TopRight,
                //             cursor: "ne-resize",
                //             desiredSize: new go.Size(6, 6),
                //             fill: "lightblue",
                //             stroke: "deepskyblue"
                //         }),
                //     },
                //     {
                //         loc: 'left',
                //         data: $(go.Shape, { //左
                //             alignment: go.Spot.Left,
                //             cursor: "w-resize",
                //             desiredSize: new go.Size(8, 8),
                //             fill: "lightblue",
                //             stroke: "deepskyblue",
                //             strokeWidth: 2
                //         })
                //     },
                //     {
                //         loc: 'right',
                //         data: $(go.Shape, {
                //             //右
                //             alignment: go.Spot.Right,
                //             cursor: "e-resize",
                //             desiredSize: new go.Size(8, 8),
                //             fill: "lightblue",
                //             stroke: "deepskyblue",
                //             strokeWidth: 2
                //         })
                //     },
                //     {
                //         loc: 'bottomLeft',
                //         data: $(go.Shape, { //左下
                //             alignment: go.Spot.BottomLeft,
                //             cursor: "se-resize",
                //             desiredSize: new go.Size(6, 6),
                //             fill: "lightblue",
                //             stroke: "deepskyblue"
                //         }),
                //     },
                //     {
                //         loc: 'bottom',
                //         data: $(go.Shape, { //下
                //             alignment: go.Spot.Bottom,
                //             cursor: "s-resize",
                //             desiredSize: new go.Size(6, 6),
                //             fill: "lightblue",
                //             stroke: "deepskyblue"
                //         }),
                //     },
                //     {
                //         loc: 'bottomRight',
                //         data: $(go.Shape, { //右下
                //             alignment: go.Spot.BottomRight,
                //             cursor: "sw-resize",
                //             desiredSize: new go.Size(6, 6),
                //             fill: "lightblue",
                //             stroke: "deepskyblue"
                //         })
                //     }
                // ]

                // pointList.forEach(p => {
                //     if (pointNum === 'all') {
                //         arr.push(p.data)
                //     } else {
                //         pointNum.forEach(a => {
                //             if (a === p.loc) {
                //                 arr.push(p.data)
                //             }
                //         })
                //     }

                // })

                return $(
                    go.Adornment,
                    "Spot", {
                        locationSpot: go.Spot.Right
                    },
                    $(go.Placeholder),
                    [...arr]
                );
            }
            /**
             * @description 缩放规则
             * @param {String} type 要进行缩放的属性
             * @param {String} targetType 缩放对比目标（width、height）
             * @param {Number} multiple 缩放比例
             * 
             */
            function scalingRules(type, targetType, multiple) {
                return [
                    new go.Binding(
                        type,
                        "",
                        (o) => {
                            let w = Number(o.size.split(' ')[0])
                            let h = Number(o.size.split(' ')[1])
                            if (targetType === 'width') {
                                return w * multiple
                            }
                            return h * multiple
                        }
                    ).makeTwoWay()
                ]
            }
            // 选中时的外框样式
            let nodeSelectionAdornmentTemplate = $(
                go.Adornment,
                "Auto",
                $(go.Shape, {
                    fill: null,
                    stroke: "deepskyblue",
                    strokeWidth: 1.5,
                    strokeDashArray: [4, 2],
                }),
                $(go.Placeholder)
            );
            // 节点统一样式（不可缩放、不可旋转）
            function nonScalableAndRotateNodeStyle() {
                return [{
                        // selectable: true, //可选择的
                        // selectionAdorned: true, // 选中时是否出现选择框
                        // selectionObjectName: "SHAPE",//要选择的对象的名称
                        // zOrder: 1, //层级，越大越上面
                        selectionAdornmentTemplate: nodeSelectionAdornmentTemplate, //选中时的框样式
                        locationSpot: go.Spot.Center, //位置是形状的中心
                        locationObjectName: "SHAPE",
                        contextMenu: partContextMenu, //右键菜单
                        selectionObjectName: "hanleSelectionNode", //选择
                        toolTip: $(
                            // 工具提示
                            "ToolTip",
                            $(
                                go.TextBlock, {
                                    margin: 4,
                                },
                                new go.Binding("text", "nodeName")
                            )
                        ),
                    },
                    new go.Binding(
                        "location",
                        "loc",
                        go.Point.parse
                    ).makeTwoWay(go.Point.stringify),
                ];
            }
            // 节点统一样式（可缩放、旋转）
            function nodeStyle() {
                return [{
                        resizable: true, //可调整形状大小
                        resizeObjectName: "SHAPE", //可调整形状对应名字
                        rotatable: true, //可旋转
                        rotateObjectName: "hanleSelectionNode", //旋转形状而不旋转标签
                    },
                    nonScalableAndRotateNodeStyle(),
                ];
            }
            // 节点统一样式（不可缩放、可旋转）
            function nonScalableNodeStyle() {
                return [{
                        rotatable: true, //可旋转
                        rotateObjectName: "SHAPE", //旋转形状而不旋转标签
                    },
                    nonScalableAndRotateNodeStyle(),
                ];
            }
            //文本节点样式
            function textNodeStyle() {
                return [{
                        resizable: true, //可缩放
                        resizeObjectName: "selectionNode", //可调整形状对应名字
                        rotatable: true, //可旋转
                        rotateObjectName: "selectionNode", //旋转形状而不旋转标签
                        selectionAdornmentTemplate: nodeSelectionAdornmentTemplate, //选中时的框样式
                        locationSpot: go.Spot.Center, //位置是形状的中心
                        locationObjectName: "selectionNode",
                        contextMenu: partContextMenu, //右键菜单
                        selectionObjectName: "selectionNode", //选择
                        toolTip: $(
                            // 工具提示
                            "ToolTip",
                            $(
                                go.TextBlock, {
                                    margin: 4,
                                },
                                new go.Binding("text", "nodeName")
                            )
                        )
                    },
                    new go.Binding(
                        "location",
                        "loc",
                        go.Point.parse
                    ).makeTwoWay(go.Point.stringify),
                ]
            }
            //调色板文本样式
            function leftTextNodeStyle() {
                return [{
                        editable: false, //文本是否可编辑
                        maxSize: new go.Size(200, NaN),
                        wrap: go.TextBlock.WrapFit,
                        font: '500 12px Arial',
                        stroke: '#fff',
                        text: '铁鞋',
                        margin: 5
                    },
                    new go.Binding("text", 'nodeName').makeTwoWay(),
                    new go.Binding('visible', 'textVisible').makeTwoWay()
                ]
            }
            //股道等节点样式
            function NodeStyleForLine() {
                return [{
                        rotatable: true, //可旋转
                        rotateObjectName: "hanleSelectionNode", //旋转形状而不旋转标签
                        resizable: true, //可调整形状大小
                        resizeObjectName: "SHAPE", //可调整形状对应名字
                        // resizeAdornmentTemplate: zoomPointStyle(['Left','Right']), //缩放点样式
                        rotateObjectName: "hanleSelectionNode", //旋转形状而不旋转标签
                    },
                    nonScalableAndRotateNodeStyle(),
                ];
            }
            //普通端口
            function myMakePort(arrayName, sideId, portId, x, y) {
                return $(
                    go.Panel,
                    "Vertical",
                    new go.Binding("itemArray", arrayName), {
                        alignment: new go.Spot(x, y, 0, 0),
                        itemTemplate: $(
                            go.Panel, {
                                _side: sideId, // 内部属性，以便更容易地判断在哪一侧
                                fromLinkable: true,
                                toLinkable: true,
                                cursor: "pointer",
                                portId: portId,
                            },
                            $(
                                go.Shape,
                                "Rectangle", {
                                    stroke: null,
                                    strokeWidth: 0,
                                    desiredSize: new go.Size(5, 5),
                                    margin: 0,
                                    fill: "transparent",
                                    mouseEnter: function (e, port) {
                                        // 端口参数将是此形状
                                        if (!e.diagram.isReadOnly) {
                                            port.fill = "rgba(255,0,255,1)"; //端口颜色
                                        }
                                    },
                                    mouseLeave: function (e, port) {
                                        port.fill = "transparent";
                                    },
                                },
                                new go.Binding(
                                    "fill",
                                    "isHighlighted",
                                    function (h) {
                                        return h ? "#FF0000" : "#BFBFBF";
                                    }
                                ).ofObject()
                            )
                        ),
                    }
                );
            }
            //股道端口
            function MakePortForLine(itemPortId, sideId, portId, x, y) {
                return $(
                    go.Panel,
                    "Vertical", {
                        itemArray: [{
                            portColor: "#d6effc",
                            portId: itemPortId,
                        }, ],
                    }, {
                        alignment: new go.Spot(x, y, 0, 0),
                        itemTemplate: $(
                            go.Panel, {
                                _side: sideId, // 内部属性，以便更容易地判断在哪一侧
                                fromLinkable: false,
                                toLinkable: true,
                                cursor: "pointer",
                                portId: portId,
                            },
                            $(go.Shape, "Rectangle", {
                                stroke: null,
                                strokeWidth: 0,
                                desiredSize: new go.Size(5, 5),
                                margin: 0,
                                fill: "transparent",
                                mouseEnter: function (e, port) {
                                    // 端口参数将是此形状
                                    if (!e.diagram.isReadOnly) {
                                        port.fill = "rgba(255,0,255,1)"; //端口颜色
                                    }
                                },
                                mouseLeave: function (e, port) {
                                    port.fill = "transparent";
                                },
                            })
                        ),
                    }
                );
            }
            //变电所端口
            function substationMakePort(
                arrayName,
                sideId,
                portId,
                spot1,
                spot2,
                x,
                y
            ) {
                return $(
                    go.Panel,
                    "Vertical",
                    new go.Binding("itemArray", arrayName), {
                        // row: 1,
                        // column: 1,
                        alignment: new go.Spot(x, y, 0, 0),
                        itemTemplate: $(
                            go.Panel, {
                                _side: sideId, // 内部属性，以便更容易地判断在哪一侧
                                fromSpot: spot1,
                                toSpot: spot2,
                                fromLinkable: true,
                                toLinkable: false,
                                cursor: "pointer",
                                portId: portId,
                            },
                            $(go.Shape, "Circle", {
                                stroke: null,
                                strokeWidth: 0,
                                desiredSize: new go.Size(5, 5),
                                margin: 0,
                                fill: "#fff",
                                mouseEnter: function (e, port) {
                                    // 端口参数将是此形状
                                    if (!e.diagram.isReadOnly) {
                                        port.fill = "rgba(255,0,255,1)"; //端口颜色
                                    }
                                },
                                mouseLeave: function (e, port) {
                                    port.fill = "#fff";
                                },
                            })
                        ),
                    }
                );
            }
            //股道
            this.myDiagram.nodeTemplateMap.add(
                "straightLine",
                $(
                    go.Node,
                    "Vertical",
                    NodeStyleForLine(), {
                        resizeAdornmentTemplate: zoomPointStyle(['Left', 'Right']), //缩放点样式
                    },
                    $(
                        go.Panel,
                        "Spot", {
                            name: "hanleSelectionNode",
                        },
                        new go.Binding("angle").makeTwoWay(),
                        $(go.Shape, "LineH", {
                                margin: 5,
                                name: "SHAPE", // 命名以便上述属性可以引用此GraphObject
                            },
                            new go.Binding(
                                "desiredSize",
                                "size",
                                go.Size.parse
                            ).makeTwoWay(go.Size.stringify),
                            new go.Binding("stroke",
                                "", (h) => {
                                    let redLine = ['commonLine', 'forkFront'],
                                        blueLine = ['contraposition', 'noFault'],
                                        greenLine = ['location', 'section'],
                                        yellowLine = ['guide'],
                                        skyBlue = ['specialLine'];
                                    if (redLine.includes(h.trackType)) {
                                        return "#FF0000";
                                    }
                                    if (blueLine.includes(h.trackType)) {
                                        return "#0000FF";
                                    }
                                    if (greenLine.includes(h.trackType)) {
                                        return "#00FF00";
                                    }
                                    if (yellowLine.includes(h.trackType)) {
                                        return "#FFFF00";
                                    }
                                    if (skyBlue.includes(h.trackType)) {
                                        return "#4BA9E5";
                                    }
                                    return h.stroke;
                                }
                            ).makeTwoWay(),
                            new go.Binding(
                                "strokeWidth",
                                "",
                                (o) => {
                                    return Number(o.size.split(' ')[1])
                                }
                            ).makeTwoWay(go.Size.stringify),
                        ),
                        // 端口
                        MakePortForLine("top0", "top1", "top1", 0.5, 0.5), //中
                        MakePortForLine("left0", "left1", "left1", 0, 0.5), //左
                        MakePortForLine("right0", "right1", "right1", 1, 0.5) //右
                    ),
                    $(go.TextBlock,
                        leftTextNodeStyle()
                    )
                )
            );
            //铁鞋图片
            this.myDiagram.nodeTemplateMap.add(
                'ironShoes',
                $(
                    go.Node,
                    'Vertical',
                    nodeStyle(), {
                        selectionObjectName: "SHAPE", //选择
                    },
                    new go.Binding("angle").makeTwoWay(),
                    $(
                        go.Panel,
                        'Position',
                        $(
                            go.Picture,
                            ironShoesImg, //在vue中，使用引用变量的方式绑定图片
                            {
                                name: 'SHAPE',
                                background: 'transparent',
                                margin: 5
                            },

                            new go.Binding(
                                'flip',
                                'flip',
                                go.Binding.parseEnum(
                                    go.GraphObject,
                                    go.GraphObject.FlipHorizontal
                                )
                            ),
                            new go.Binding(
                                "desiredSize",
                                "size",
                                go.Size.parse
                            ).makeTwoWay(go.Size.stringify)
                        ),
                    ),
                    $(go.TextBlock,
                        leftTextNodeStyle()
                    )
                )
            );
            //机车头图片
            this.myDiagram.nodeTemplateMap.add(
                'carHead',
                $(
                    go.Node,
                    'Vertical',
                    nodeStyle(), {
                        selectionObjectName: "SHAPE", //选择
                    },
                    new go.Binding("angle").makeTwoWay(),
                    $(
                        go.Panel,
                        'Position',
                        $(
                            go.Picture,
                            carHeadImg, //在vue中，使用引用变量的方式绑定图片
                            {
                                name: 'SHAPE',
                                margin: 5,
                                background: 'transparent',
                            },
                            new go.Binding(
                                'flip',
                                'flip',
                                go.Binding.parseEnum(
                                    go.GraphObject,
                                    go.GraphObject.FlipHorizontal
                                )
                            ),
                            new go.Binding(
                                "desiredSize",
                                "size",
                                go.Size.parse
                            ).makeTwoWay(go.Size.stringify)
                        ),
                    ),
                    $(go.TextBlock,
                        leftTextNodeStyle()
                    )
                )
            );
            //灯
            this.myDiagram.nodeTemplateMap.add(
                "circularLight",
                $(
                    go.Node,
                    "Vertical",
                    nodeStyle(), {
                        selectionObjectName: "light", //选择
                    },
                    new go.Binding("angle").makeTwoWay(),
                    $(go.Panel, 'Auto', {
                            name: 'light'
                        },
                        $(
                            go.Panel,
                            "Spot",
                            $(go.Shape, "Circle", {
                                    margin: 5,
                                    stroke: "#000",
                                    name: "SHAPE", // 命名以便上述属性可以引用此GraphObject
                                    fill: "#fff",
                                },
                                new go.Binding(
                                    "desiredSize",
                                    "size",
                                    go.Size.parse
                                ).makeTwoWay(go.Size.stringify),
                                scalingRules('strokeWidth', 'width', 1 / 21),
                            ),

                        ),
                        $(
                            go.Panel,
                            "Spot",
                            $(go.Shape, "Circle", {
                                    strokeWidth: 1,
                                    stroke: "#000",
                                },
                                scalingRules('width', 'width', 15 / 21),
                                scalingRules('height', 'width', 15 / 21),
                                scalingRules('strokeWidth', 'width', 1 / 21),
                                new go.Binding("fill", "", function (h) {
                                    let type = h.data.lightState,
                                        color = '#FF0000'
                                    switch (type) {
                                        case '1':
                                            color = '#fff'
                                            break;
                                        case '2':
                                            color = '#FFFF00' //黄
                                            break;
                                        case '3':
                                            color = '#FF0000' //红
                                            break;
                                        case '4':
                                            color = '#00FF00' //绿
                                            break;
                                        case '5':
                                            color = '#0095FF'
                                            break;
                                    }
                                    return color;
                                }).ofObject())
                        ),
                    ),
                    $(go.TextBlock,
                        leftTextNodeStyle()
                    )
                )
            );
            //双灯
            this.myDiagram.nodeTemplateMap.add(
                "doubleLight",
                $(
                    go.Node,
                    "Vertical",
                    nodeStyle(), {
                        selectionObjectName: "SHAPE", //选择
                    },
                    new go.Binding("angle").makeTwoWay(),
                    $(
                        go.Panel,
                        "Horizontal", {
                            margin: 5,
                            name: "SHAPE",
                        },
                        new go.Binding(
                            "desiredSize",
                            "size",
                            go.Size.parse
                        ).makeTwoWay(go.Size.stringify),
                        // scalingRules('width','height',55 / 25),
                        // scalingRules('height','width',25 / 55),
                        $(go.Shape, {
                                geometry: go.Geometry.parse(
                                    //自定义图形轨迹
                                    "M0 0 L0 20 M0 10 L3 10"
                                ),
                                background: "transparent",
                                stroke: "#fff",
                                margin: new go.Margin(4, 0, 4, 4)
                            },
                            scalingRules('width', 'width', 3 / 55),
                            scalingRules('height', 'height', 20 / 25),
                            scalingRules('strokeWidth', 'height', 2 / 25)

                        ),
                        $(
                            go.Panel,
                            'Auto', {
                                margin: new go.Margin(4, 0, 4, 0)
                            },
                            $(
                                go.Panel,
                                "Node",
                                $(go.Shape, "Circle", {
                                        stroke: "#000",
                                        fill: "#fff",
                                    },
                                    scalingRules('width', 'height', 21 / 25),
                                    scalingRules('height', 'height', 21 / 25),
                                    scalingRules('strokeWidth', 'height', 1 / 25),
                                )
                            ),
                            $(
                                go.Panel,
                                "Node",
                                $(go.Shape, "Circle", {
                                        stroke: "#000",
                                    },
                                    new go.Binding("fill", '', (o) => {
                                        let color = '#fff'
                                        switch (o.lightState) {
                                            case '1':
                                                color = '#0095FF';
                                                break;
                                            case '2':
                                                color = '#FF0000';
                                                break;
                                            case '3':
                                                color = '#00FF00';
                                                break;
                                        }
                                        return color
                                    }).makeTwoWay(),
                                    scalingRules('width', 'height', 15 / 25),
                                    scalingRules('height', 'height', 15 / 25),
                                    scalingRules('strokeWidth', 'height', 1 / 25),
                                )
                            )

                        ),
                        $(
                            go.Panel,
                            'Auto', {
                                margin: new go.Margin(4, 4, 4, 0)
                            },
                            $(
                                go.Panel,
                                "Node",
                                $(go.Shape, "Circle", {
                                        name: "SHAPE",
                                        stroke: "#000",
                                        fill: "#fff",
                                    },
                                    scalingRules('width', 'height', 21 / 25),
                                    scalingRules('height', 'height', 21 / 25),
                                    scalingRules('strokeWidth', 'height', 1 / 25),
                                )
                            ),
                            $(
                                go.Panel,
                                "Node",
                                $(go.Shape, "Circle", {
                                        stroke: "#000",
                                    },
                                    new go.Binding("fill", '', (o) => {
                                        let color = '#fff'
                                        switch (o.lightState) {
                                            case '1':
                                                color = '#fff';
                                                break;
                                            case '2':
                                                color = '#fff';
                                                break;
                                            case '3':
                                                color = '#FFFF00';
                                                break;
                                        }
                                        return color
                                    }).makeTwoWay(),
                                    scalingRules('width', 'height', 15 / 25),
                                    scalingRules('height', 'height', 15 / 25),
                                    scalingRules('strokeWidth', 'height', 1 / 25),
                                )
                            )

                        ),
                    ),
                    $(go.TextBlock,
                        leftTextNodeStyle()
                    )
                )
            );
            //普通绝缘节
            this.myDiagram.nodeTemplateMap.add(
                "breakpoint",
                $(
                    go.Node,
                    "Vertical",
                    NodeStyleForLine(), {
                        resizeAdornmentTemplate: zoomPointStyle(['Top', 'Bottom', 'Left', 'Right']), //缩放点样式
                    },
                    $(
                        go.Panel,
                        "Spot", {
                            name: "hanleSelectionNode",
                        },
                        new go.Binding("angle", "angle").makeTwoWay(),
                        $(go.Shape, "LineV", {
                                margin: 5,
                                name: "SHAPE", // 命名以便上述属性可以引用此GraphObject
                            },
                            new go.Binding(
                                "desiredSize",
                                "size",
                                go.Size.parse
                            ).makeTwoWay(go.Size.stringify),
                            new go.Binding("stroke").makeTwoWay(),
                            scalingRules('strokeWidth', 'width', 1)
                        )
                    ),
                    $(go.TextBlock,
                        leftTextNodeStyle()
                    )
                )
            );
            //超限绝缘节
            this.myDiagram.nodeTemplateMap.add(
                "breakpoint2",
                $(
                    go.Node,
                    "Vertical",
                    nodeStyle(),
                    $(
                        go.Panel,
                        "Auto", {
                            name: "hanleSelectionNode",
                        },
                        new go.Binding("angle").makeTwoWay(),
                        $(go.Shape, "Circle", {
                                name: "SHAPE",
                                desiredSize: new go.Size(10, 10),
                                background: "transparent",
                                stroke: "#fff",
                                fill: "transparent",
                                strokeWidth: 1,
                                margin: 5,
                            },
                            new go.Binding(
                                "desiredSize",
                                "size",
                                go.Size.parse
                            ).makeTwoWay(go.Size.stringify),
                            scalingRules('width', 'height', 1),
                            scalingRules('strokeWidth', 'height', 1 / 10),
                            new go.Binding(
                                "stroke"
                            ).makeTwoWay(),
                        ),
                        $(
                            go.Shape,
                            "LineV", {
                                name: "SHAPE",
                                desiredSize: new go.Size(1, 10),
                                background: "transparent",
                                stroke: "#fff",
                                fill: "transparent",
                                strokeWidth: 1,
                            },
                            new go.Binding(
                                "desiredSize",
                                "size",
                                go.Size.parse
                            ).makeTwoWay(go.Size.stringify),
                            scalingRules('width', 'height', 1 / 10),
                            scalingRules('strokeWidth', 'height', 1 / 10),
                            new go.Binding(
                                "stroke"
                            ).makeTwoWay(),
                        )
                    ),
                    $(go.TextBlock,
                        leftTextNodeStyle()
                    )
                )
            );
            //窗口
            this.myDiagram.nodeTemplateMap.add(
                "rectangle",
                $(
                    go.Node,
                    "Vertical",
                    nodeStyle(),
                    $(
                        go.Panel,
                        "Spot", {
                            name: "hanleSelectionNode",
                        },
                        new go.Binding("angle").makeTwoWay(),
                        $(go.Shape, "Rectangle", {
                                fill: 'transparent',
                                margin: 5,
                                name: "SHAPE", // 命名以便上述属性可以引用此GraphObject
                                strokeWidth:2
                            },
                            new go.Binding(
                                "desiredSize",
                                "size",
                                go.Size.parse
                            ).makeTwoWay(go.Size.stringify),
                            new go.Binding("stroke").makeTwoWay()
                        )
                    ),
                    $(go.TextBlock,
                        leftTextNodeStyle()
                    )
                )
            );
            //文本
            this.myDiagram.nodeTemplateMap.add(
                "rectangleText",
                $(
                    go.Node,
                    "Vertical",
                    textNodeStyle(),
                    $(
                        go.Panel,
                        "Spot", {
                            name: "selectionNode",
                        },
                        new go.Binding("background").makeTwoWay(),
                        new go.Binding("angle").makeTwoWay(),
                        new go.Binding(
                            "desiredSize",
                            "size",
                            go.Size.parse
                        ).makeTwoWay(go.Size.stringify),
                        $(
                            go.TextBlock, {
                                editable: false, //文本是否可编辑
                                wrap: go.TextBlock.WrapFit,
                                verticalAlignment: go.Spot.Center //垂直居中
                            },
                            new go.Binding("margin", '', (o) => {
                                return o.underline ? new go.Margin(3, 5, 0, 5) : 5
                            }).makeTwoWay(),
                            new go.Binding("textAlign").makeTwoWay(),
                            new go.Binding("font", '', (o) => {
                                let num = o.fontWeight ? '900' : '500'
                                return `${num} ${o.fontSize}px Lato, Helvetica, Arial, sans-serif`
                            }).makeTwoWay(),
                            new go.Binding("text").makeTwoWay(),
                            new go.Binding("stroke").makeTwoWay()
                        )
                    ),
                    $(go.Shape, 'LineH', {
                            height: 1,
                            background: 'transparent',
                            stroke: '#fff',
                            fill: '#fff',
                            strokeWidth: 2,
                        },
                        new go.Binding('visible', 'underline').makeTwoWay(),
                        new go.Binding("width", '', (o) => {
                            let width = o.size.split(' ')[0]
                            return Number(width)
                        }).makeTwoWay(), ),
                    $(go.TextBlock,
                        leftTextNodeStyle()
                    )
                )
            );
            //半自动闭塞
            this.myDiagram.nodeTemplateMap.add(
                "semiAutomaticBlock",
                $(
                    go.Node,
                    "Vertical",
                    nodeStyle(),
                    $(
                        go.Panel,
                        "Spot", {
                            name: "hanleSelectionNode",
                        },
                        new go.Binding("angle").makeTwoWay(),
                        $(
                            go.Shape,
                            "Arrow", {
                                name: "SHAPE", // 命名以便上述属性可以引用此GraphObject
                                margin: 5,
                                strokeWidth: 3,
                                stroke: "#FF0000",
                                fill: "#FF0000",
                            },
                            new go.Binding("stroke").makeTwoWay(),
                            new go.Binding("fill", "stroke").makeTwoWay(),
                            new go.Binding(
                                "desiredSize",
                                "size",
                                go.Size.parse
                            ).makeTwoWay(go.Size.stringify)
                        )
                    ),
                    $(go.TextBlock,
                        leftTextNodeStyle()
                    )
                )
            );
            // 变电所
            this.myDiagram.nodeTemplateMap.add(
                "substation",
                $(
                    go.Node,
                    "Vertical", {
                        rotateObjectName: "hanleSelectionNode", //旋转形状而不旋转标签
                    },
                    nodeStyle(),
                    $(
                        go.Panel,
                        "Spot", {
                            name: "hanleSelectionNode",
                        },
                        new go.Binding("angle").makeTwoWay(),
                        $(
                            go.Shape, {
                                name: "SHAPE",
                                margin: 5,
                                geometry: go.Geometry.parse(
                                    //自定义图形轨迹
                                    "M0 0 L120 0 L120 80 L0 80 L0 0 M0 80 L60 0 L120 80"
                                ),
                                background: "transparent",
                                stroke: "#BFBFBF",
                                strokeWidth: 2,
                            },
                            new go.Binding(
                                "desiredSize",
                                "size",
                                go.Size.parse
                            ).makeTwoWay(go.Size.stringify)
                        ),
                        substationMakePort(
                            "leftArray",
                            "left1",
                            "substation1",
                            go.Spot.Left,
                            go.Spot.Left,
                            0,
                            0.5
                        ),
                        substationMakePort(
                            "topArray",
                            "top1",
                            "substation2",
                            go.Spot.Top,
                            go.Spot.Top,
                            0.5,
                            0
                        ),
                        substationMakePort(
                            "bottomArray",
                            "bottom1",
                            "substation3",
                            go.Spot.Bottom,
                            go.Spot.Bottom,
                            0.5,
                            1
                        ),
                        substationMakePort(
                            "rightArray",
                            "right1",
                            "substation4",
                            go.Spot.Right,
                            go.Spot.Right,
                            1,
                            0.5
                        )
                    ),
                    $(go.TextBlock,
                        leftTextNodeStyle()
                    )
                )
            );
            // 当不在任何部分上时，提供图表背景的上下文菜单
            this.myDiagram.contextMenu = $(
                "ContextMenu",
                makeButton(
                    "粘贴",
                    function (e, obj) {
                        e.diagram.commandHandler.pasteSelection(
                            e.diagram.toolManager.contextMenuTool.mouseDownPoint
                        );
                    },
                    function (o) {
                        return o.diagram.commandHandler.canPasteSelection(
                            o.diagram.toolManager.contextMenuTool.mouseDownPoint
                        );
                    }
                )
            );
            // 替换linkTemplateMap中的默认链接模板
            this.myDiagram.linkTemplate = $(
                go.Link, // the whole link panel
                {
                    curve: go.Link.JumpOver,
                    corner: 5, //线圆角
                    toShortLength: 0,
                    // relinkableFrom: true,
                    // relinkableTo: true,
                    reshapable: true,
                    resegmentable: true,
                    // 如果将调色板中的某个节点拖到该节点上，其轮廓将变为绿色
                    mouseDragEnter: function (e, link) {
                        link.isHighlighted = true;
                    },
                    mouseDragLeave: function (e, link) {
                        link.isHighlighted = false;
                    },
                    mouseEnter: function (e, link) {
                        link.findObject("HIGHLIGHT").stroke =
                            "rgba(255,0,255,0.5)";
                    },
                    mouseLeave: function (e, link) {
                        link.findObject("HIGHLIGHT").stroke = "#fff";
                    },
                    // selectionAdorned: false,
                    contextMenu: $(
                        "ContextMenu",
                        makeButton(
                            "删除",
                            function (e, obj) {
                                e.diagram.commandHandler.deleteSelection();
                            },
                            function (o) {
                                return o.diagram.commandHandler.canDeleteSelection();
                            }
                        )
                    ), //右键菜单
                },
                new go.Binding("routing", "", function (h) {
                    let nodeArr = ["districtKiosk", "substation"];
                    // if (
                    //     nodeArr.includes(h.fromNode.data.category) ||
                    //     nodeArr.includes(h.toNode.data.category)
                    // ) {
                    //     return go.Link.AvoidsNodes;
                    // }
                    // return go.Link.Normal;
                    return go.Link.AvoidsNodes;
                }).ofObject(),
                new go.Binding("points").makeTwoWay(),
                $(
                    go.Shape, // the highlight shape, normally transparent
                    {
                        name: "HIGHLIGHT",
                        stroke: "#fff",
                        strokeWidth: 3,
                    },
                    new go.Binding("stroke", "isHighlighted", function (h) {
                        return h ? "chartreuse" : "#fff";
                    }).ofObject(),
                    new go.Binding("strokeWidth", "isHighlighted", function (
                        h
                    ) {
                        return h ? 4 : 3;
                    }).ofObject()
                )
            );
            // 当用户单击图表的背景时，删除所有突出显示
            this.myDiagram.click = function (e) {
                _this.formData = {};
                _this.isTrack = false;
                e.diagram.commit(function (d) {
                    d.clearHighlighteds();
                }, "no highlighteds");
            };

            this.load(); // 从一些JSON文本加载初始图表

            // 初始化页面左侧的调色板
            this.myPalette = $(
                go.Palette,
                "myPaletteDiv", // 必须命名或引用DIV HTML元素
                {
                    // 使用自定义淡入淡出而不是默认动画
                    "animationManager.initialAnimationStyle": go.AnimationManager.None,
                    InitialAnimationStarting: _this.animateFadeDown, // 相反，使用此函数设置动画
                    nodeTemplateMap: _this.myDiagram.nodeTemplateMap, // 共享myDiagram使用的模板，这样左侧调色板中的图就和拖拽出的图一致了
                    initialScale: 1, //图形尺寸
                    hoverDelay: 40, // 控制在显示装饰之前静止等待的时间（毫秒）
                    model: new go.GraphLinksModel([
                        // 指定调色板的内容
                        {
                            businessId: '', //业务id
                            category: "rectangleText",
                            size: '50 30',
                            textAlign: 'center',
                            fontSize: 18,
                            fontWeight: false,
                            textVisible: true,
                            underline: false,
                            background: 'rgba(0,0,0,0)',
                            text: "文本",
                            nodeName: "文本",
                            stroke: "#fff",
                            angle: 0,
                            customData: [] //自定义信息
                        },
                        {
                            category: "circularLight",
                            businessId: '',
                            nodeName: "信号灯",
                            size: '21 21',
                            textVisible: true,
                            angle: 0,
                            lightState: '1', //灯状态
                            customData: [] //自定义信息
                        },
                        {
                            category: "doubleLight",
                            businessId: '',
                            lightState: '1', //灯状态
                            size: '55 25',
                            nodeName: "信号灯1",
                            textVisible: true,
                            angle: 0,
                            customData: [] //自定义信息
                        },
                        {
                            category: 'ironShoes',
                            businessId: '',
                            nodeName: "铁鞋",
                            size: '60 20',
                            angle: 0,
                            textVisible: true,
                            customData: [], //自定义信息
                            flip: 'None' //FlipHorizontal
                        },
                        {
                            category: 'carHead',
                            businessId: '',
                            nodeName: "机车头",
                            angle: 0,
                            textVisible: true,
                            size: '50 40',
                            customData: [], //自定义信息
                            flip: 'None' //FlipHorizontal
                        },
                        {
                            category: "straightLine",
                            businessId: '',
                            nodeName: "股道",
                            stroke: '#FF0000',
                            textVisible: true,
                            angle: 0,
                            size: "60 2",
                            customData: [], //自定义信息
                            trackType: 'commonLine' //普通股道
                        },
                        {
                            category: "breakpoint",
                            businessId: '',
                            nodeName: "普通绝缘节",
                            textVisible: true,
                            stroke: '#fff',
                            size: '2 10',
                            angle: 0,
                            customData: [], //自定义信息
                        },
                        {
                            category: "breakpoint2",
                            businessId: '',
                            nodeName: "超限绝缘节",
                            size: '10 10',
                            stroke: '#fff',
                            textVisible: true,
                            angle: 0,
                            customData: [], //自定义信息
                        },
                        {
                            category: "rectangle",
                            businessId: '',
                            text: "窗口",
                            nodeName: "窗口",
                            stroke: '#fff',
                            size: '60 10',
                            textVisible: true,
                            angle: 0,
                            customData: [], //自定义信息
                        },
                        {
                            category: "semiAutomaticBlock",
                            businessId: '',
                            text: "半自动闭塞",
                            nodeName: "半自动闭塞",
                            stroke: "#FF0000",
                            size: '23 5',
                            angle: 0,
                            textVisible: true,
                            customData: [], //自定义信息
                        },
                        {
                            category: "substation",
                            businessId: "",
                            text: "变电所",
                            nodeName: "变电所",
                            sourceKey: "self",
                            size: "60 40",
                            angle: 0,
                            businessId: '',
                            stroke: "#fff",
                            textVisible: true,
                            customData: [], //自定义信息
                            leftArray: [{
                                portColor: "#fae3d7",
                                portId: "left0",
                            }, ],
                            topArray: [{
                                portColor: "#d6effc",
                                portId: "top0",
                            }, ],
                            bottomArray: [{
                                portColor: "#ebe3fc",
                                portId: "bottom0",
                            }, ],
                            rightArray: [{
                                portColor: "#fadfe5",
                                portId: "right1",
                            }, ],

                        }


                    ]),
                }
            );
            this.myPalette.model.undoManager = this.myDiagram.model.undoManager; // 共享UndoManager！
            //缩略图
            let myOverview = $(go.Overview, "myOverviewDiv", {
                observed: this.myDiagram,
            });
            let events = [{
                    event: 'BackgroundSingleClicked',
                    name: '单击背景'
                },
                {
                    event: "ObjectSingleClicked",
                    name: "单击节点",
                },
                {
                    event: "SelectionDeleting",
                    name: "删除前",
                },
                {
                    event: "LinkDrawn",
                    name: "创建连线",
                },
                {
                    event: 'SelectionMoved',
                    name: '拖拽'
                },
                {
                    event: 'ExternalObjectsDropped',
                    name: '拖拽生成'
                },
                {
                    event: 'ClipboardPasted',
                    name: '粘贴'
                }
            ];
            //事件监听
            events.forEach((item) => {
                this.myDiagram.addDiagramListener(item.event, function (e) {
                    if (item.event === 'BackgroundSingleClicked') {
                        _this.formData = {};
                        _this.customFormList = [];
                        return
                    }
                    if (item.event === 'ClipboardPasted') {
                        console.log('粘贴', e)
                        e.diagram.selection.each(item => {
                            _this.formData = item.data;
                            _this.customFormList = item.data.customData;
                        })
                    }
                    if (item.event === "ObjectSingleClicked") {
                        let data = e.subject.part.data;
                        // console.log("左击：", e.subject.part.category);
                        _this.formData = data;
                        _this.customFormList = data.customData;
                    }
                    if (item.event === 'ExternalObjectsDropped') {
                        let nodeData = _this.myDiagram.findNodeForKey('defaultId'); //用例获取选中的节点或线
                        if (nodeData) {
                            _this.myDiagram.model.removeNodeData(nodeData.data);
                        }
                        e.diagram.selection.each(item => {
                            _this.formData = item.data;
                            _this.customFormList = item.data.customData;
                            _this.publicChange('textVisible', false)
                        })
                    }
                });
            });
        },
    }
}